package com.qipay.cpaccount.impl;

import com.qipay.baas.model.CpAccountTradlog;
import com.qipay.baas.model.Order;
import com.qipay.cpaccount.CpAccountTradLogService;
import com.qipay.mapper.CpAccountTradlogMapper;
import io.jsonwebtoken.lang.Assert;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class CpAccountTradLogServiceImpl implements CpAccountTradLogService {

    @Autowired
    CpAccountTradlogMapper cpAccountTradlogMapper;

    @Override
    @Transactional
    public void setOrderFinish(Order order) {
        CpAccountTradlog cpAccountTradlog = new CpAccountTradlog();
        cpAccountTradlog.setAccountType((byte) 1);
        cpAccountTradlog.setCpId(order.getCpId());
        cpAccountTradlog.setAmount(order.getActualAmount());
        cpAccountTradlog.setChannelType(order.getChannelType());
        cpAccountTradlog.setTotal(order.getAmount());
        cpAccountTradlog.setTradeNo(order.getTradeNo());
        cpAccountTradlog.setCreateTime(new Date());
        cpAccountTradlogMapper.insert(cpAccountTradlog);

        if (order.getAgentId() != null && order.getAgentId() > 0) {
            CpAccountTradlog agentTradLog = new CpAccountTradlog();
            agentTradLog.setAccountType((byte) 2);
            agentTradLog.setCpId(order.getAgentId());
            agentTradLog.setAmount(order.getFee() - order.getAgentFee());
            agentTradLog.setChannelType(order.getChannelType());
            agentTradLog.setTotal(order.getAmount());
            agentTradLog.setTradeNo(order.getTradeNo());
            agentTradLog.setCreateTime(new Date());
            cpAccountTradlogMapper.insert(agentTradLog);
        }
    }

    @Override
    public List<CpAccountTradlog> list(List<Long> cpIdList, String from, String to) {

        // check
        Assert.isTrue(CollectionUtils.isNotEmpty(cpIdList));
        Assert.isTrue(StringUtils.isNotBlank(from) && StringUtils.isNotBlank(to));

        return cpAccountTradlogMapper.list(cpIdList, from, to);
    }

}
